package cn.quevo.ucenter.server.controller;

import cn.quevo.core.entity.UserInfoDetails;
import cn.quevo.core.exception.CustomException;
import cn.quevo.spring.SpringController;
import cn.quevo.ucenter.core.ResponseEntityBuild;
import cn.quevo.ucenter.core.entity.ClientInfo;
import cn.quevo.ucenter.core.entity.OauthRequest;
import cn.quevo.ucenter.core.entity.OauthResponse;
import cn.quevo.ucenter.core.enums.OauthResultStatusEnum;
import cn.quevo.ucenter.core.enums.ResponseTypeEnum;
import cn.quevo.ucenter.core.token.OAuthIssuer;
import cn.quevo.ucenter.core.token.impl.OAuthIssuerImpl;
import cn.quevo.ucenter.server.entity.OauthCode;
import cn.quevo.ucenter.server.entity.query.OauthClientQuery;
import cn.quevo.ucenter.server.service.OauthClientService;
import cn.quevo.ucenter.server.service.OauthCodeService;
import cn.quevo.ucenter.server.util.UcenterUtil;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.URISyntaxException;

/**
 * 授权请求Controller
 * 
 * @author July july_sky@foxmail.com
 * @date 2018年3月23日 上午11:05:42
 * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
 * @version 1.0
 */
@Controller("oauthCodeController")
public class OauthCodeController extends SpringController {

//    private final static Logger log = LoggerFactory.getLogger(OauthCodeController.class);
    @Resource(name = "oauthCodeService")
    private OauthCodeService oauthCodeService;
    @Resource(name = "oauthClientService")
    private OauthClientService oauthClientService;

    /**
     * 获取授权码
     * 
     * @author July july_sky@foxmail.com
     * @date 2018年3月23日 下午6:54:18
     * @param model
     * @param request
     * @return
     * @throws URISyntaxException
     * @throws CustomException
     */
    @RequestMapping("/authorize")
    public Object authorize(Model model, HttpServletRequest request)
            throws URISyntaxException, CustomException {
        // 构建OAuth 授权请求
        OauthRequest oauthRequest = new OauthRequest(request);
        OauthClientQuery oauthClientQuery = new OauthClientQuery();
        oauthClientQuery.setClientId(oauthRequest.getClientId());
        ClientInfo clientInfo = this.oauthClientService.getOauthClient(oauthClientQuery);
        // 验证客户端是否存在
        if (clientInfo == null) {
            return ResponseEntityBuild.build(HttpStatus.OK, new OauthResponse(OauthResultStatusEnum.INVALID_CLIENT));
        }
        // 验证用户是否已登录
        UserInfoDetails userInfoDetails = UcenterUtil.getUserInfoDetails();
        if (userInfoDetails == null) {
            model.addAttribute("clientId", oauthRequest.getClientId());
            return "login";
        }
        String authCode = this.createOauthCode(oauthRequest, userInfoDetails.getUserId());
        OauthResponse response = new OauthResponse();
        response.set("code", authCode).setRedirectUri(clientInfo.getRedirectUri());
        return ResponseEntityBuild.found(response);
    }

    /**
     * 创建授权码
     * 
     * @author July july_sky@foxmail.com
     * @date 2018年3月23日 下午5:18:21
     * @param oauthRequest
     * @param userId
     * @return
     * @throws CustomException
     */
    private String createOauthCode(OauthRequest oauthRequest, Long userId)
            throws CustomException {
        // 创建授权码
        OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl();
        String authCode = oauthIssuerImpl.authorizationCode();
        // responseType目前仅支持CODE，另外还有TOKEN
        if (!ResponseTypeEnum.CODE.toString().equalsIgnoreCase(oauthRequest.getResponseType())) {
            return authCode;
        }
        OauthCode oauthCode = new OauthCode();
        oauthCode.setClientId(oauthRequest.getClientId());
        oauthCode.setAuthCode(authCode);
        oauthCode.setUserId(userId);
        oauthCodeService.createOauthCode(oauthCode);
        return authCode;
    }
}
